package increment1;

import java.util.Map;
import java.util.TreeMap;

/**
 * The class Person represents a person supposed to carry out a Task.
 * @author Rolf Schmidt
 * @version 1.0
 */
public class Person {

	/**
	 * contains the name of the person
	 */
	private String name;
	/**
	 * contains the number of hours all the tasks this person is associated with will take to complete
	 */
	private int hours;
	/**
	 * contains a list of the task IDs this person is associated with
	 */
	private TreeMap<String , Task> tasks;

	public Person() {
		super();
		this.name="nobody";
		this.hours=0;
		this.tasks = new TreeMap<String , Task>();
	}

	@Override
	public String toString() {
		final String H_LINE = "---------------------------------------";
		StringBuffer sb = new StringBuffer(H_LINE);

		sb.append("\nName: " + name);
		sb.append("\nHours: " + hours); 
		sb.append("\nTasks: " + getTaskList()); 
		sb.append("\n" + H_LINE + "\n");
		return sb.toString();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (hours != other.hours)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (tasks == null) {
			if (other.tasks != null)
				return false;
		} else if (!tasks.equals(other.tasks))
			return false;
		return true;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		if (name == null || name.equals("")) {
			this.name = "nobody";
		}
		else {
			this.name = name;
		}
	}

	/**
	 * @return the hours
	 */
	public int getHours() {
		return hours;
	}

	/**
	 * 
	 * @return the list of task IDs associated with this Person as an ArrayList of Tasks
	 */
	public TreeMap<String , Task> getTasks() {
		return this.tasks;
	}
	
	/**
	 * @return the list of task IDs associated with this Person as a String
	 */
	public String getTaskList() {
		String result = "";

		int count = 0;
		int size = tasks.size();
		for (Map.Entry<String, Task> entry : tasks.entrySet()) {
			result += entry.getValue().getId();
			count++;
			if (count < size)
				result += ", ";
		}
		return result;
	}

	/**
	 * adds a task and calculates the total number of hours
	 */
	public void addTask(Task task) {
		if (task == null)
			return;

		String taskId = task.getId();
		if (tasks.containsKey(taskId))
			return;
		
		if (!task.getPerson().equals(name))
			task.setPerson(name);

		tasks.put(taskId, task);
		this.hours += task.getDuration();
	}
}
